<?php

namespace app\controllers\shop;

use app\controllers\common\CommonController;
use app\models\shop\LuckyDrawModel;
use app\models\shop\LuckyDrawRecordModel;
use app\models\shop\ScoreModel;
use app\models\shop\ShopUserModel;
use app\models\shop\VoucherModel;
use app\models\shop\VoucherTypeModel;
use yii;
use yii\web\ShopController;

class LuckyDrawController extends ShopController {

    public $enableCsrfValidation = false; //禁用CSRF令牌验证，可以在基类中设置

//    public function behaviors() {
//        return [
//            'token' => [
//                'class' => 'yii\filters\ShopFilter', //调用过滤器
////                'only' => ['single'],//指定控制器应用到哪些动作
//                'except' => ['do-draw','group-order-process'],//指定控制器不应用到哪些动作
//            ]
//        ];
//    }

    /**
     * 抽奖方法
     * @return [array] [抽奖情况]
     */
    public function actionDoDraw() {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数

            $must = ['id'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }

            $model = new LuckyDrawModel();
            $recordModel = new LuckyDrawRecordModel();
            $userModel = new ShopUserModel();
            $where['id'] = $params['id'];
            $where['status'] = 1;
            $info = $model->do_one($where);
            if ($info['status'] != 200){
                return result(500, "活动已关闭");
            }
            $userWhere['id'] = yii::$app->session['user_id'];
            $userInfo = $userModel->do_one($userWhere);
            if ($userInfo['status'] != 200) {
                return result(500, "用户信息有误");
            }
            if (($userInfo['data']['draw_num'] + $userInfo['data']['everyone_draw_num'] + $userInfo['data']['every_day_draw_num']) <= 0) {
                return result(500, "用户抽奖次数不足");
            }

            $eventPrizes = json_decode($info['data']['event_prizes'],true);

            //将数组按中奖率由高到低排序
            $probability = array_column($eventPrizes,'probability');
            array_multisort($probability,SORT_DESC,$eventPrizes);
            //当中奖率最低的奖品中奖率低于1%,需计算出系数
            $coefficient = 1;
            foreach ($eventPrizes as $k=>$v){
                if ($v['probability'] < 1 && $v['probability'] != 0) {
                    $coefficient = 1 / $v['probability'];
                }
            }
            $proArr = [];
            $totalProbability = 0; //总中奖几率
            foreach ($eventPrizes as $k=>$v){
                //判断奖品是否被抽完
                $recordWhere['lucky_draw_id'] = $info['data']['id'];
                $recordWhere['limit'] = false;
                $recordWhere['prize_id'] = $v['id'];
                $recordInfo = $recordModel->do_select($recordWhere);
                if ($recordInfo['status'] == 200 && $recordInfo['count'] >= $v['number']){
                    $temp['v'] = 0; //当奖品被抽完，权重设置为0
                } else {
                    $temp['v'] = $coefficient * $v['probability']; //中奖权重(系数*中奖几率)
                }
                $temp['id'] = $v['id'];
                $temp['name'] = $v['name'];
                $temp['probability'] = $v['probability'];
                $proArr[] = $temp;
                $totalProbability += $v['probability'];
            }
            if (count($eventPrizes) < 8) {
                $temp['id'] = 9; //id=9表示未中奖
                $temp['name'] = '谢谢参与';
                $temp['v'] = $coefficient * (100 - $totalProbability);
                $temp['probability'] = 100 - $totalProbability;
                $proArr[] = $temp;
            }
            //将数组按权重由低到高排序
            $v = array_column($proArr,'v');
            if (array_sum($v) <= 0){ //当总权重小于等于0，表示奖品全部抽完
                return result(500, "活动已结束");
            }
            array_multisort($v,$proArr);
            // 奖品等级奖品权重数组
            $arr = [];
            foreach ($proArr as $key => $val) {
                //当有中奖率低于1%的,总抽奖次数未达到总权重一半时，该商品权重设为0
                unset($recordWhere['prize_id']);
                $recordInfo = $recordModel->do_select($recordWhere);
                if (($recordInfo['status'] == 204 || ($recordInfo['status'] == 200 && $recordInfo['count'] <= (array_sum($v) / 2))) && $val['probability'] < 1){
                    $arr[$val['id']] = 0;
                } else {
                    $arr[$val['id']] = $val['v'];
                }
            }
            // 中奖 id
            $rid = $this->get_rand($arr);

            /**模拟抽奖测试**/
//            $i = 0;
//            while ( $i < 2000) {  //抽奖次数
//                $rid = $this->get_rand($arr);
//                $res[] = $rid;
//                $i++;
//            }
//            // 统计奖品出现次数
//            $result = array_count_values($res);
//            asort($result);
//            foreach ($result as $id => $times) {
//                foreach ($proArr as $gifts) {
//                    if($id == $gifts['id']){
//                        $response[$gifts['name']] = $times;
//                    }
//                }
//            }
//            var_dump($response);
//            die;

            //增加中奖记录
            $recordData['lucky_draw_id'] = $info['data']['id'];
            $recordData['user_id'] = yii::$app->session['user_id'];
            $recordData['type'] = 4; //默认值（循环找到奖品替换）
            $recordData['prize_id'] = 9; //默认值
            $recordData['name'] = '谢谢参与'; //默认值
            foreach ($eventPrizes as $k=>$v) {
                if ($rid == $v['id']){
                    $recordData['type'] = $v['type'];
                    $recordData['prize_id'] = $v['id'];
                    $recordData['name'] = $v['name'];
                    if ($v['type'] == 2){ //积分奖励(自动发放)
                        //修改用户积分
                        $recordData['integral'] = $v['integral'];
                        $recordData['status'] = 1;
                        $userData['score'] = $v['integral'] + $userInfo['data']['score'];
                        $userData['total_score'] = $v['integral'] + $userInfo['data']['total_score'];
                        $userRes = $userModel->do_update($userWhere,$userData);
                        if ($userRes['status'] == 200){
                            //添加积分记录
                            $scoreModel = new ScoreModel();
                            $scoreData['`key`'] = yii::$app->session['key'];
                            $scoreData['merchant_id'] = yii::$app->session['merchant_id'];
                            $scoreData['user_id'] = yii::$app->session['user_id'];
                            $scoreData['score'] = $v['integral'];
                            $scoreData['content'] = '抽奖赠送积分';
                            $scoreData['type'] = 1;
                            $scoreData['status'] = 1;
                            $scoreModel->add($scoreData);
                        }
                    } elseif ($v['type'] == 3) { //优惠券奖励(自动发放)
                        $recordData['coupon'] = $v['coupon'];
                        $recordData['status'] = 1;
                        $typeModel = new VoucherTypeModel();
                        $voucherModel = new VoucherModel();
                        $typeWhere['id'] = $v['coupon'];
                        $typeInfo = $typeModel->find($typeWhere);
                        if ($typeInfo['status'] == 200 && $typeInfo['data']['status'] == 1 && (int)$typeInfo['data']['to_date1'] > time() && $typeInfo['data']['count'] > $typeInfo['data']['send_count']){ //优惠券正常才可以发放
                            $cc = new CommonController();
                            $voucherData['`key`'] = yii::$app->session['key'];
                            $voucherData['merchant_id'] = yii::$app->session['merchant_id'];
                            $voucherData['cdkey'] = $cc->generateCode();
                            $voucherData['user_id'] = yii::$app->session['user_id'];
                            $voucherData['price'] = $typeInfo['data']['price'];
                            $voucherData['full_price'] = $typeInfo['data']['full_price'];
                            $voucherData['start_time'] = time();
                            $voucherData['end_time'] = strtotime($typeInfo['data']['to_date']);
                            $voucherData['type_name'] = $typeInfo['data']['name'];
                            $voucherData['type_id'] = $v['coupon'];
                            $voucherData['status'] = 1;
                            $result = $voucherModel->add($voucherData);
                            if ($result['status'] == 200){
                                //更新优惠券个数
                                $typeData['send_count'] = $typeInfo['data']['send_count'] + 1;
                                $typeData['id'] = $v['coupon'];
                                $typeModel->update($typeData);
                            }
                        }
                    }
                }
            }
            $recordModel->do_add($recordData);
            //减去抽奖次数
            $userData = [];
            if ($userInfo['data']['every_day_draw_num'] > 0) {
                $userData['every_day_draw_num'] = $userInfo['data']['every_day_draw_num'] - 1;
            } elseif ($userInfo['data']['everyone_draw_num'] > 0) {
                $userData['everyone_draw_num'] = $userInfo['data']['everyone_draw_num'] - 1;
            } else {
                $userData['draw_num'] = $userInfo['data']['draw_num'] - 1;
            }
            $userModel->do_update($userWhere,$userData);
            return result(200, "请求成功",['id'=>$recordData['prize_id'],'name'=>$recordData['name']]);

        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 抽奖算法
     * @param  array  $proArr 奖品等级奖品权重数组
     * @return [int]         中奖奖品等级
     */
    public function get_rand($proArr = array()) {
        if(empty($proArr)) die;
        $rid = '';
        // 概率数组的总权重
        $proSum = array_sum($proArr);
        // 概率数组循环
        foreach ($proArr as $k => $proCur) {
            // 从 1 到概率总数中任意取值
            $randNum = mt_rand(1, $proSum);
            // 判断随机数是否在概率权重中
            if ($randNum <= $proCur) {
                // 取出奖品 id
                $rid = $k;
                break;
            } else {
                // 如果随机数不在概率权限中，则不断缩小总权重，直到从奖品数组中取出一个奖品
                $proSum -= $proCur;
            }
        }
        unset($proArr);
        return $rid;
    }

    public function actionOne() {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数

            $model = new LuckyDrawModel();
            $recordModel = new LuckyDrawRecordModel();
            $where['status'] = 1;
            $array = $model->do_one($where);
            if ($array['status'] != 200){
                return result(500, "活动已关闭");
            }

            $recordWhere['field'] = "shop_lucky_draw_record.name as prize_name,shop_user.nickname,shop_user.avatar";
            $recordWhere['join'][] = ['left join', 'shop_user', 'shop_user.id = shop_lucky_draw_record.user_id'];

            $recordWhere['shop_lucky_draw_record.lucky_draw_id'] = $array['data']['id'];
            $recordWhere['<>'] = ['shop_lucky_draw_record.type',4];
            $recordWhere['limit'] = false;
            $recordInfo = $recordModel->do_select($recordWhere);
            if ($recordInfo['status'] == 200) {
                $array['data']['winning_list'] = $recordInfo['data'];
            } else {
                $array['data']['winning_list'] = [];
            }
            $array['data']['start_time'] = date('Y-m-d H:i:s',$array['data']['start_time']);
            $array['data']['end_time'] = date('Y-m-d H:i:s',$array['data']['end_time']);
            $array['data']['event_prizes'] = json_decode($array['data']['event_prizes'],true);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    //抽奖次数
    public function actionDrawNum() {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数

            $userModel = new ShopUserModel();
            $userWhere['id'] = yii::$app->session['user_id'];
            $userInfo = $userModel->do_one($userWhere);
            if ($userInfo['status'] == 200) {
                $data['draw_num'] = $userInfo['data']['draw_num'] + $userInfo['data']['every_day_draw_num'] + $userInfo['data']['everyone_draw_num'];
                return result(200, "请求成功",$data);
            } else {
                $userInfo;
            }
        } else {
            return result(500, "请求方式错误");
        }
    }

    //我的奖品
    public function actionMyPrize() {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数

            $model = new LuckyDrawRecordModel();
            $where['user_id'] = yii::$app->session['user_id'];
            $where['<>'] = ['type',4];
            if (isset($params['limit'])) {
                $where['limit'] = $params['limit'];
                $where['page'] = $params['page'];
            } else {
                $where['limit'] = false;
            }
            $array = $model->do_select($where);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    //领取奖品
    public function actionUpdate($id) {
        if (yii::$app->request->isPut) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            $must = ['name','phone','addr','address'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }

            $model = new LuckyDrawRecordModel();
            $where['id'] = $id;
            $where['user_id'] = yii::$app->session['user_id'];
            $data['user_info'] = json_encode($params,JSON_UNESCAPED_UNICODE);

            $array = $model->do_update($where,$data);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    //积分抽奖
    public function actionScore($id) {
        if (yii::$app->request->isPut) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            $model = new ShopUserModel();
            $drawModel = new LuckyDrawModel();
            $where['id'] = yii::$app->session['user_id'];
            $userInfo = $model->do_one($where);
            if ($userInfo['status'] != 200) {
                return result(500, "用户信息有误");
            }
            $drawWhere['id'] = $id;
            $drawWhere['status'] = 1;
            $drawInfo = $drawModel->do_one($drawWhere);
            if ($drawInfo['status'] != 200) {
                return result(500, "活动已结束");
            }
            if ($drawInfo['data']['points_exchange_is_open'] == 0) {
                return result(500, "该活动未开启积分兑换");
            }
            if ($userInfo['data']['score'] < $drawInfo['data']['points_exchange']) {
                return result(500, "积分不足");
            }
            $data['score'] = $userInfo['data']['score'] - $drawInfo['data']['points_exchange'];
            $data['draw_num'] = $userInfo['data']['draw_num'] + 1;

            $array = $model->do_update($where,$data);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }




}
